<template>
  <div class="dialog-overlay" v-if="visible" @click.self="closeDialog">
    <div class="dialog-content modal-main">
      <div class="dialog-header modal-header">
        <h1 class="dialog-title">编辑回放任务</h1>
        <button class="close-button" @click="closeDialog">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>

      <div class="dialog-body">
        <div class="form-group">
          <div style="display: flex; align-items: center; flex: 1; position: relative;">
            <label class="form-label required">任务名称</label>
            <input
              type="text"
              class="form-input"
              v-model="taskName"
              placeholder="请输入任务名称"
              :class="{'error': taskNameError}"
              required
              maxlength="50"
              :onchange="handleChange"
              style="margin-left: 12px; flex: 1;"
            >
            <span v-if="taskNameError" class="error-message">必填输入</span>
          </div>
        </div>
        <!-- 传输穿梭框 -->
        <div class="shuttle-container">
          <shuttleBox
          :taskName="taskName || ''"
          :availableName="props.paramName"
          :parameters="props.parameters"
          v-model:selectedParams="selectedParams"
          />
        </div>
      </div>
      <div class="dialog-footer modal-footer">
        <button class="tech-btn-warn cancel-btn" @click="closeDialog">取消</button>
        <button class="tech-btn confirm-btn" @click="handleConfirm">确认</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from 'vue'
import shuttleBox from './shuttleBox.vue'
import API from "@/views/playbackTask/playbackTask.api.ts";
const mode = localStorage.getItem('mode')
const props = defineProps<{
  visible: boolean,
  paramName: string,
  parameters: Array<any>,
  viewSettings: any
}>()

const selectedParams = ref<Array<{ value: string; label: string; type:string }>>([])

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'confirm', value: { name: string; description: string }): void
  (e: 'success', value: { type: string; content: string; duration: number }): void;
}>()

const taskName = ref<string>('');
const taskDescription = ref('')
const taskNameError = ref(false)


const closeDialog = () => {
  emit('update:visible', false)
  taskName.value = ''
  taskDescription.value = ''
}

// 确认方法
const handleConfirm = async () => {
  if (!taskName.value?.trim()) {
    taskNameError.value = true
    return
  }

  try {
    // 先校验任务名称是否存在
    const checkRes = await API.taskNameCheck(taskName.value)
    // 递归处理参数，保持树形结构
    const processParams = (params: any[]) => {
      return params.map(item => {
        const result = {
          id: item.id || item.value,
          name: item.name || item.label,
          type: item.type,
          children: item.children,
        }
        if (item.children && item.children.length > 0) {
          result.children = processParams(item.children)
        }

        return result
      })
    }

    let params: any = {
      name: taskName.value,
      parameters: JSON.stringify(processParams(selectedParams.value))
    }
    if (mode === 'online') {
      params.userId = localStorage.getItem('userId')
    }
    // 保存视图设置
    const viewSet = { ... props.viewSettings }
    // 只提取viewSet中leftA 删除其他对象
    const viewSetParams = Object.keys(viewSet).filter(key => key.includes('leftA'))
    const viewSetParamsObj: any = {}
    viewSetParams.forEach(key => {
      viewSetParamsObj[key] = viewSet[key]
    })
    params.viewSettings = JSON.stringify(viewSetParamsObj)
    if (!checkRes.data) {
      API.saveTask(params).then((res:any) => {
        if (res && res.code == 200) {
          emit('success', {
            type:'success',
            content: '新增成功',
            duration: 500
          });
          taskNameError.value = false
          emit('confirm', {
            name: taskName.value || '',
            description: taskDescription.value
          })
          closeDialog();
        }
      })
    } else {
      API.updateTask(params).then((res:any) => {
        if (res && res.code == 200) {
          emit('success', {
            type:'success',
            content: '编辑成功',
            duration: 500
          });
          taskNameError.value = false
          emit('confirm', {
            name: taskName.value || '',
            description: taskDescription.value
          })
          closeDialog();
        }
      })
    }
  } catch (error) {
    console.error('Failed to save task:', error)
  }
}

function handleChange() {
  if (!taskName.value?.trim()) {
    taskNameError.value = true
    return
  }
  taskNameError.value = false
}

const taskModelRef = ref<HTMLElement | null>(null)
onMounted(async () => {
  if (props.paramName) {
    taskName.value = props.paramName;
    // 如果是编辑模式，需要加载已选参数
    try {
      const res: any = await API.queryAllTask();
      if (res && res.code === 200) {
        const task = res.data.find((item: any) => item.name === props.paramName);
        if (task) {
          const parsedParams = JSON.parse(task.parameters);
          selectedParams.value = parsedParams.map((param: any) => ({
            value: param.id,
            label: param.name,
            type: param.type,
            children: param.children?.map((child: any) => ({
              value: child.id,
              label: child.name,
              type: child.type
            }))
          }));
        }
      }
    } catch (error) {
      console.error('Failed to load task parameters:', error);
    }
  }
})
</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  //background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  //overflow-y: auto;
  //box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  padding: 16px 20px;
  //border-bottom: 1px solid rgba(30, 64, 175, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
}

.close-button {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  color: var(--text-color);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-button:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: var(--global-color-black);
}

.dialog-body {
  padding: 10px 20px;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

.form-group {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: nowrap;
  //border: 1px solid var(--border-color-base);
  border-radius: 8px;
  padding: 12px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color);
  min-width: 20px;
}

.form-label.required::after {
  content: '*';
  color: var(--error-color);
  margin-left: 4px;
}

.form-input {
  width: 100%;
  padding: 6px 10px;
  border: 1px solid var(--input-border-color);
  border-radius: 4px;
  font-size: 13px;
  color: var(--text-color);
  background: var(--input-background);
}

.form-input.error {
  border-color: var(--error-color);
}

.error-message {
  color: var(--error-color);
  font-size: 12px;
  margin-top: 1px;
  position: absolute;
  bottom: -20px;
  left: 80px;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.dialog-footer {
  padding: 12px 16px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  position: sticky;
  bottom: 0;

}
.tech-btn-warn{
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
}
.tech-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
}

.cancel-btn {
  background: rgb(241, 245, 249);
  border: 1px solid rgb(203, 213, 225);
  color: #64748b;
}

.cancel-btn:hover {
  background: rgb(226, 232, 240);
  border-color: rgb(148, 163, 184);
}

.confirm-btn {
  background: rgb(237, 243, 255);
  border: 1px solid rgb(196, 216, 255);
  color: #1e3a8a;
}

.confirm-btn:hover {
  background: rgb(161, 197, 252);
  border-color: rgb(184, 204, 255);
}

/* 确认覆盖弹窗样式 */
.confirm-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1100;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 400px;
}

.confirm-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.confirm-dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e3a8a;
  margin: 0;
}

.confirm-dialog-text {
  color: #64748b;
  margin: 0;
}

.confirm-dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 1024px) {
  .dialog-content {
    width: 85%;
    max-width: 650px;
  }
  .dialog-title {
    font-size: 15px;
  }
  .form-label {
    font-size: 12px;
  }
  .form-input {
    font-size: 11px;
    padding: 4px 8px;
  }
  .error-message {
    font-size: 10px;
  }
  .tech-btn {
    font-size: 12px;
    padding: 6px 12px;
  }
  .confirm-dialog-title {
    font-size: 16px;
  }
  .confirm-dialog-text {
    font-size: 12px;
  }
  .shuttle-container {
    height: 400px;
  }
}

</style>
